<template>
  <div class="batch-details">
    <el-card class="mb-4">
      <template #header>
        <div class="flex items-center justify-between">
          <h2 class="text-xl">批次号：{{ batchNo }}</h2>
          <el-tag :type="statusType" size="large">{{ statusText }}</el-tag>
        </div>
      </template>

      <el-row :gutter="20" class="mb-6">
        <el-col :span="6">
          <el-statistic title="总链接数" :value="progress?.totalCount || 0">
            <template #prefix>
              <el-icon><Link /></el-icon>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic
              title="成功数"
              :value="progress?.successCount || 0"
              value-style="color: #67C23A"
          >
            <template #prefix>
              <el-icon><CircleCheckFilled /></el-icon>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic
              title="失败数"
              :value="progress?.failureCount || 0"
              value-style="color: #F56C6C"
          >
            <template #prefix>
              <el-icon><CircleCloseFilled /></el-icon>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-progress
              type="circle"
              :percentage="calculateProgress"
              :status="progressStatus"
              :width="60"
              style="margin-bottom: 20px"
          />
        </el-col>
      </el-row>

      <el-table
          v-loading="loading"
          :data="details"
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa' }"
          border
      >
        <el-table-column type="index" :index="getTableIndex" width="60" align="center" />
        <el-table-column prop="targetUrl" label="目标URL" min-width="300">
          <template #default="{ row }">
            <el-tooltip :content="row.targetUrl" placement="top">
              <span class="truncate block">{{ row.targetUrl }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="newUrl" label="外链URL" min-width="300">
          <template #default="{ row }">
            <el-tooltip :content="row.newUrl" placement="top">
              <a class="truncate block" :href= 'row.newUrl' target="_blank">{{ row.newUrl }}</a>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="executeTime" label="最后执行时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.executeTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastError" label="详情" min-width="200">
          <template #default="{ row }">
            <template v-if="row.status === 'SUCCESS'">
              <el-text type="success">评论成功</el-text>
            </template>
            <template v-else-if="row.status === 'FAILED'">
              <el-tooltip :content="row.errorMessage" placement="top">
                <el-text type="danger">{{ truncateError(row.errorMessage) }}</el-text>
              </el-tooltip>
            </template>
            <template v-else-if="row.status === 'PENDING'">
              <el-text type="info">等待执行</el-text>
            </template>
            <template v-else>
              <el-text type="primary">处理中</el-text>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="flex justify-end mt-4">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes, prev, pager, next, jumper"
        />
      </div>

      <div class="flex justify-end gap-4 mt-6">
        <el-button
            v-if="hasPendingTasks"
            type="primary"
            @click="resumeBatch"
            :loading="resuming"
        >
          继续执行
        </el-button>
        <el-button @click="goBack" :icon="Back">返回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {computed, onMounted, onUnmounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {useCommentsStore} from '@/stores/adminComment'
import {format} from 'date-fns'
import {Back, CircleCheckFilled, CircleCloseFilled, Link, VideoPlay} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'

const route = useRoute()
const router = useRouter()
const commentsStore = useCommentsStore()

const batchNo = route.params.id
// 使用 ref 来管理本地状态
const progress = ref(null)
const details = ref([])
const timer = ref(null)
const loading = ref(true)
const resuming = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 检查是否有待执行任务
const hasPendingTasks = computed(() => {
  return details.value.some(task => task.status === 'PENDING')
})

const resumeBatch = async () => {
  try {
    resuming.value = true
    await commentsStore.resumeTask(batchNo)
    ElMessage.success('已开始执行待处理任务')
    await fetchData()
    // 启动轮询
    // if (!timer.value) {
    //   startPolling()
    // }
  } catch (error) {
    console.error('Failed to resume batch:', error)
    ElMessage.error('执行失败')
  } finally {
    resuming.value = false
  }
}

// 计算表格序号
const getTableIndex = (index) => {
  return (currentPage.value - 1) * pageSize.value + index + 1
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 计算进度
const calculateProgress = computed(() => {
  return progress.value?.progressPercentage || 0
})

// 进度条状态
const progressStatus = computed(() => {
  if (!progress.value) return 'normal'
  switch (progress.value.status) {
    case 'COMPLETED':
      return 'success'
    case 'FAILED':
      return 'exception'
    case 'PARTIALLY_COMPLETED':
      return 'warning'
    default:
      return 'normal'
  }
})

// 状态类型
const statusType = computed(() => {
  if (!progress.value) return 'info'
  switch (progress.value.status) {
    case 'PROCESSING':
      return 'primary'
    case 'COMPLETED':
      return 'success'
    case 'PARTIALLY_COMPLETED':
      return 'warning'
    case 'FAILED':
      return 'danger'
    default:
      return 'info'
  }
})

const statusText = computed(() => {
  if (!progress.value) return '未开始'
  const statusMap = {
    'PENDING': '等待中',
    'PROCESSING': '执行中',
    'COMPLETED': '已完成',
    'PARTIALLY_COMPLETED': '部分完成',
    'FAILED': '执行失败'
  }
  return statusMap[progress.value.status] || progress.value.status
})

const isCompleted = computed(() => {
  return progress.value && ['COMPLETED', 'PARTIALLY_COMPLETED', 'FAILED'].includes(progress.value.status)
})

const getStatusType = (status) => {
  const typeMap = {
    'SUCCESS': 'success',
    'FAILED': 'danger',
    'PENDING': 'info',
    'PROCESSING': 'primary'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'SUCCESS': '成功',
    'FAILED': '失败',
    'PENDING': '等待中',
    'PROCESSING': '处理中'
  }
  return statusMap[status] || status
}

const formatTime = (time) => {
  if (!time) return '--'
  return format(new Date(time), 'yyyy年MM月dd日 HH时mm分ss秒')
}

const truncateError = (error) => {
  if (!error) return ''
  return error.length > 30 ? error.substring(0, 30) + '...' : error
}

const fetchData = async () => {
  try {
    loading.value = true
    // 获取进度
    progress.value = await commentsStore.getBatchProgress(batchNo)

    // 获取分页详情
    const response = await commentsStore.getBatchDetails(batchNo, {
      current: currentPage.value,
      pageSize: pageSize.value
    })

    details.value = response.records
    total.value = response.total

    // 如果任务已完成且没有定时器，则不需要继续轮询
    if (isCompleted.value) {
      stopPolling()
    }
  } catch (error) {
    console.error('Failed to fetch data:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const startPolling = () => {
  // 如果任务已完成，不需要开始轮询
  if (isCompleted.value) {
    return
  }
  fetchData()
  timer.value = setInterval(fetchData, 60000)
}

const stopPolling = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

const goBack = () => {
  router.push('/admin-comment/list')
}

onMounted(async () => {
  // 首次加载数据
  await fetchData()
  // 只有在任务未完成时才开始轮询
  // if (!isCompleted.value) {
  //   startPolling()
  // }
})

onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
.batch-details {
  max-width: 1200px;
  margin: 24px auto;
  padding: 0 16px;
}

.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-card__header) {
  padding: 16px 20px;
}

:deep(.el-pagination) {
  justify-content: flex-end;
  margin-top: 16px;
}
</style>